#include "RefractionMaterial.h"
#include "Integrator.h"

Color RefractionMaterial::shade(const Scene * scene, const Ray & ray, const IntersectResult &intersect, const TraceState & traceState) const {
#if 1
	Color refraction = material ? material->shade(scene, ray, intersect, traceState) : Colors::White;
	refraction *= strength;
	Double kr = fresnel(ray.dir, intersect.normal, ior);
	if (kr < 1 && RAND > kr) {
		Vector3 refractDir = refract(ray.dir, intersect.normal, ior);
		if (!refractDir.isZero()) {
			refraction *= scene->getIntegrator()->Li(scene, Ray(intersect.position, refractDir), traceState);
		}
		return refraction;
	} else {
		Vector3 reflectDir = reflect(ray.dir, intersect.normal);
		refraction *= scene->getIntegrator()->Li(scene, Ray(intersect.position, reflectDir), traceState);
		return refraction;
	}
#else
	Color refraction;
	Double kr = fresnel(ray.dir, intersect.normal, ior);
	if (kr < 1) {
		Vector3 refractDir = refract(ray.dir, intersect.normal, ior);
		if (!refractDir.isZero()) {
			refraction = scene->getIntegrator()->Li(scene, Ray(intersect.position, refractDir), traceState);
			refraction *= 1 - kr;
		}
	}
	Vector3 reflectDir = reflect(ray.dir, intersect.normal);
	Color reflection = scene->getIntegrator()->Li(scene, Ray(intersect.position, reflectDir), traceState);
	reflection *= kr;

	refraction += reflection;
	refraction *= strength;

	return material ? refraction *= material->shade(scene, ray, intersect, traceState) : refraction;
#endif
}

Color RefractionMaterial::getTransparentColor(const Scene * scene, const Ray & ray, const IntersectResult & intersect) const {
	return material ? strength *= material->getTransparentColor(scene, ray, intersect) : strength * Colors::White;
}
